/*
 * @Author: nengwu 409791297@qq.com
 * @Date: 2020-06-25 22:16:16
 * @LastEditors: mylesshie@gmail.com
 * @LastEditTime: 2020-10-18 20:49:21
 * @description:
 */

import React, { useCallback, useEffect, useState, useRef } from 'react'
import { ScrollView, Text, View, SafeAreaView, Dimensions, Image, Modal } from 'react-native'
import { WebView } from 'react-native-webview'
import { Button } from 'react-native-elements'
import { useSelector, useDispatch } from 'react-redux'
import HTML from 'react-native-render-html'
import AntDesign from 'react-native-vector-icons/AntDesign'
import ImageViewer from 'react-native-image-zoom-viewer'

import CommentBar from '@/components/CommentBar'
import CommentItem from '@/components/CommentItem'
import NewsItem from '@/components/NewsItem'
import ShareBox from '@/components/ShareBox'
import RenderHTMLImage from '@/components/RenderHtmlImage'

import * as mainActions from '@/actions/main'
import * as userActions from '@/actions/user'
import { styles } from './styles'

const NewsDetail = ({ navigation, route }) => {
  console.log('NewsDetail')
  const detail = useSelector(state => state.main.detail)
  const [loading, setLoading] = useState(true)
  const dispatch = useDispatch()
  const [commentList, seCommentList] = useState([])
  const [recommendNews, setRecommendNews] = useState([])
  const [pageNum, setPageNum] = useState(1)
  const [pageEnd, setPageEnd] = useState(false)
  const [isCollect, setIsCollect] = useState(false)
  const [shareVisible, setshareVisible] = useState(false)
  const [largeImageUrl, setlargeImageUrl] = useState([])
  const [largeImgModal, setlargeImgModal] = useState(false)
  const shareRef = useRef(false)
  const pageSize = 20

  // 获取帖子详情
  const _getDetail = useCallback(() => {
    dispatch(mainActions.getArticleDetail(route.params.id)).then(res => {
      setLoading(false)
      setIsCollect(!!res.collection)
      setRecommendNews(res.recommendNews)
      navigation.setOptions({
        title: res.title,
        headerRight: () => {
          return (
            <View style={styles.headerBtn}>
              <AntDesign
                name="sharealt"
                color="#333"
                size={25}
                onPress={_toggleShare}
              />
            </View>
          )
        }
      })
    })
  }, [dispatch])

  useEffect(() => {
    _getDetail()
  }, [])
  // 切换分享弹窗
  const _toggleShare = () => {
    if (shareRef.current) {
      setshareVisible(false)
      shareRef.current = false
    } else {
      setshareVisible(true)
      shareRef.current = true
    }
  }
  // 获取评论
  const _getComments = useCallback(() => {
    dispatch(
      userActions.getArticleComments(route.params.id, pageNum, pageSize)
    ).then(res => {
      if (pageNum === 1) {
        seCommentList(res.list)
      } else {
        seCommentList(commentList.concat(res.list))
      }

      setPageEnd(res.pageNum * res.pageSize >= res.total)
    })
  }, [dispatch])

  useEffect(() => {
    _getComments()
  }, [pageNum, pageSize])

  const _getMoreComments = () => {
    if (pageEnd) return
    setPageNum(pageNum + 1)
  }

  // 渲染评论列表
  const _renderCommentList = () => {
    return commentList.map(item => {
      return (
        <CommentItem
          id={item.id}
          key={item.id}
          cusNikeName={item.cusNikeName}
          createdTime={item.createdTime}
          commentDesc={item.commentDesc}
          parise={item.parise}
        />
      )
    })
  }

  // 渲染推荐新闻列表
  const _renderRecommendNews = () => {
    return recommendNews.map(item => {
      return (
        <NewsItem
          id={item.id}
          key={item.id}
          title={item.title}
          coverImgs={item.coverUrl}
          type={item.artType}
          topping={item.topping}
          inDetail
        />
      )
    })
  }

  // 发布评论成功后刷新评论列表
  const _commentSuccess = () => {
    setPageNum(1)
    _getComments()
  }

  // 图片点击事件
  const handleModalImage = src => {
    console.log(src)
    setlargeImageUrl([{
      url: src
    }])
    setlargeImgModal(true)
  }

  const onHideImageModal = () => {
    setlargeImgModal(false)
  }

  // 文档默认样式
  const tagStyles = {
    p: {
      textAlign: 'left',
      fontSize: 16,
      lineHeight: 24,
      marginTop: 20,
      marginBottom: 0,
      padding: 0,
      color: '#333'
    }
  }

  return (
    <>
      {loading ? null : (
        <>
          <SafeAreaView style={styles.wrap}>
            <ScrollView
              style={styles.container}
              contentInsetAdjustmentBehavior="automatic"
            >
              <View style={styles.newsMain}>
                <View style={styles.titleBox}>
                  <Text style={styles.title}>
                    {detail.title}
                  </Text>
                </View>
                <View style={styles.infoBox}>
                  <Text style={styles.info}>
                    来源:{detail.source} 浏览:{detail.viewCount} 作者:
                    {detail.reporter}
                  </Text>
                </View>
                <View style={styles.content}>
                  {detail.artType === 1 ? (
                    <WebView
                      source={{ uri: detail.content }}
                      style={styles.webview}
                      useWebKit={true}
                      allowsInlineMediaPlayback={true}
                    />
                  ) : (
                    <HTML
                      tagsStyles={tagStyles}
                      html={detail.content}
                      enableExperimentalPercentWidth={true}
                      imagesInitialDimensions={{width: 0, height: 0}}
                      imagesMaxWidth={Dimensions.get('window').width - 26}
                      renderers={{
                        img: (attribs, children, objectCSS, contentProps) => (
                          <RenderHTMLImage
                            uri={attribs.src}
                            onPress={(uri) => handleModalImage(uri)}
                            imagesMaxWidth={contentProps.imagesMaxWidth}
                          />
                        ),
                      }}
                    />
                  )}
                </View>
              </View>
              {recommendNews.length ? (
                <View style={styles.recommendBar} />
              ) : null}
              <View>{_renderRecommendNews()}</View>
              <View style={styles.comments}>{_renderCommentList()}</View>
              {pageEnd ? null : (
                <Button
                  type="clear"
                  onPress={_getMoreComments}
                  titleStyle={styles.getMoreText}
                  title="查看更多评论～"
                />
              )}
            </ScrollView>
            <CommentBar
              articleId={route.params.id}
              onCommentSuccess={_commentSuccess}
              isCollect={isCollect}
            />
            { shareVisible ? <ShareBox onClose={_toggleShare} title={detail.title} desc={detail.title} cover={detail.shareImg} id={detail.id} /> : null }
            <Modal visible={largeImgModal} transparent={true}>
              <ImageViewer imageUrls={largeImageUrl} onClick={onHideImageModal}/>
            </Modal>
          </SafeAreaView>
        </>
      )}
    </>
  )
}

export default NewsDetail
